﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.IO;
using System.Drawing.Drawing2D;
using System.Data.SqlClient;
using System.Data;

namespace AsianSocietyPictureUpload
{
    class AsianSocietyUploadPicturesToDatabase
    {

        private Image _Image;
        private string fileName;
        private DataTable CityUrl;
        private DataTable dtCoord;
        private int CityCount;

        public AsianSocietyUploadPicturesToDatabase()
        {
            GetCoordinates();
            SetCityUrl();         
        }

       
        public void UploadDataProcess()
        {
            CityCount = 0;

            //Need to insert loop here
            FetchImage();
            CropImage();
            ResizeImage();
            TextOverLayImage();
            SaveImageToLocalFolder();
        }

        private void SetCityUrl()
        {
        }

        private int GetNumberOfDays()
        {
            DateTime d1 = new DateTime(DateTime.Today.Year, 1, 1);
            DateTime d2 = DateTime.Now; ;
            TimeSpan diff = d2 - d1;
            int days = diff.Days;

            return (days + 1);
        }

        private void TextOverLayImage()
        {
            string CityName = Convert.ToString(dtCoord.Rows[CityCount]["CityName"]);
            int xCoord = Convert.ToInt32(dtCoord.Rows[CityCount]["XCoordinate"]);
            int yCoord = Convert.ToInt32(dtCoord.Rows[CityCount]["YCoordinate"]);

            Graphics g = Graphics.FromImage(_Image);

       //     StringFormat strFormat = new StringFormat();
      //     strFormat.Alignment = StringAlignment.Center;
       //     strFormat.LineAlignment = StringAlignment.Center;
          g.DrawString(CityName, new Font("Tahoma", 20), Brushes.White, new PointF(xCoord, yCoord));
        }

        private void GetCoordinates()
        {
            SqlConnection myConnection = new SqlConnection();
            myConnection.ConnectionString = "Data Source=HIPPO;Initial Catalog=AsiaSociety;Integrated Security=True";
            myConnection.Open();

            string SQL = "SELECT a.[CityName], b.XCoordinate, b.YCoordinate FROM [AsiaSociety].[dbo].[City] a,[AsiaSociety].[dbo].[Coordinate] b WHERE a.CityID = b.CityID";

            SqlDataAdapter adaptor = new SqlDataAdapter(SQL, myConnection);

            dtCoord = new DataTable();
            adaptor.Fill(dtCoord);

            myConnection.Close();
        }

        private void ResizeImage()
        {
            int sourceWidth = _Image.Width;
            int sourceHeight = _Image.Height;

            float nPercent = 0;
            float nPercentW = 0;
            float nPercentH = 0;

            nPercentW = ((float)980 / (float)sourceWidth);
            nPercentH = ((float)634 / (float)sourceHeight);

            if (nPercentH < nPercentW)
                nPercent = nPercentH;
            else
                nPercent = nPercentW;

            int destWidth = (int)(sourceWidth * nPercent);
            int destHeight = (int)(sourceHeight * nPercent);

            Bitmap b = new Bitmap(destWidth, destHeight);
            Graphics g = Graphics.FromImage((Image)b);
            g.InterpolationMode = InterpolationMode.HighQualityBicubic;

            g.DrawImage(_Image, 0, 0, destWidth, destHeight);
            g.Dispose();

            b.SetResolution(72.0F, 72.0F);

            _Image = (Image)b;
        }

        private void SaveImageToLocalFolder()
        {
            //Check for Folder, Create if folder does not exist
            if (!System.IO.Directory.Exists(@"C:\AsianSocietyUploadedPictures"))
                System.IO.Directory.CreateDirectory(@"C:\AsianSocietyUploadedPictures");

            if (_Image != null)
                _Image.Save(@"C:\AsianSocietyUploadedPictures\" + DateTime.Now.ToString("MM_dd_yyyy_") + fileName);
        }

        private void CropImage()
        {
            Rectangle cropArea = new Rectangle(500, 500, 3100, 2000);

            Bitmap bmpImage = new Bitmap(_Image);
            Bitmap bmpCrop = bmpImage.Clone(cropArea, bmpImage.PixelFormat);
            bmpCrop.SetResolution(72.0F, 72.0F);
            _Image = (Image)(bmpCrop);
        }

        public void FetchImage()
        {
            // Download web image
            _Image = null;
          //  this.fileName = null;

            string url = "http://lance-modis.eosdis.nasa.gov/imagery/subsets/tmp/AERONET_Beijing.2012" + GetNumberOfDays() + ".terra.250m.jpg";


            Uri uri = new Uri(url);
            fileName = Path.GetFileName(uri.LocalPath);

            _Image = DownloadImage(url);  
        }

        private Image DownloadImage(string _URL)
        {
            Image _tmpImage = null;

            try
            {
                // Open a connection
                System.Net.HttpWebRequest _HttpWebRequest = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(_URL);

                _HttpWebRequest.AllowWriteStreamBuffering = true;

                // You can also specify additional header values like the user agent or the referer: (Optional)
                //  _HttpWebRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)";
                //   _HttpWebRequest.Referer = "http://www.google.com/";

                // set timeout for 20 seconds (Optional)
                _HttpWebRequest.Timeout = 20000;

                // Request response:
                System.Net.WebResponse _WebResponse = _HttpWebRequest.GetResponse();

                // Open data stream:
                System.IO.Stream _WebStream = _WebResponse.GetResponseStream();

                // convert webstream to image
                _tmpImage = Image.FromStream(_WebStream);

                // Cleanup
                _WebResponse.Close();
                _WebResponse.Close();
            }
            catch (Exception _Exception)
            {
                // Error
                Console.WriteLine("Exception caught in process: {0}", _Exception.ToString());
                return null;
            }

            return _tmpImage;
        }
    }
}
